<template>
  <div class="home-page">
    <div class="hero-section">
      <div class="hero-content">
        <h1 class="hero-title">发现你的专属AI伙伴</h1>
        <p class="hero-subtitle">与各种性格的AI角色对话，体验不同的互动乐趣</p>
        <div class="hero-search">
          <input 
            v-model="searchKeyword" 
            @keyup.enter="searchRoles"
            placeholder="搜索角色..." 
            class="search-input"
          />
          <button @click="searchRoles" class="search-btn">搜索</button>
        </div>
      </div>
    </div>

    <div class="content-section">
      <div class="container">
        <div class="section-header">
          <h2>热门角色</h2>
          <router-link to="/roles" class="view-all">查看全部</router-link>
        </div>
        
        <div v-if="loading" class="loading-grid">
          <div v-for="i in 6" :key="i" class="role-card skeleton">
            <div class="skeleton-avatar"></div>
            <div class="skeleton-content">
              <div class="skeleton-title"></div>
              <div class="skeleton-desc"></div>
            </div>
          </div>
        </div>
        
        <div v-else class="roles-grid">
          <div 
            v-for="role in popularRoles" 
            :key="role.id" 
            class="role-card"
            @click="startChat(role)"
          >
            <div class="role-avatar">
              <img v-if="role.avatarUrl" :src="role.avatarUrl" :alt="role.name" />
              <div v-else class="avatar-placeholder">{{ role.name.charAt(0) }}</div>
            </div>
            <div class="role-info">
              <h3 class="role-name">{{ role.name }}</h3>
              <p class="role-desc">{{ role.description || '暂无描述' }}</p>
              <div class="role-stats">
                <span class="stat">
                  <span class="stat-icon">💬</span>
                  {{ role.usageCount || 0 }}
                </span>
                <span class="stat">
                  <span class="stat-icon">⭐</span>
                  {{ role.averageRating || 0 }}
                </span>
              </div>
            </div>
            <div class="role-actions">
              <button class="chat-btn">开始对话</button>
            </div>
          </div>
        </div>

        <div class="section-header">
          <h2>角色分类</h2>
        </div>
        
        <div class="categories-grid">
          <div 
            v-for="category in categories" 
            :key="category.id"
            class="category-card"
            @click="filterByCategory(category)"
          >
            <div class="category-icon">{{ category.icon }}</div>
            <h3 class="category-name">{{ category.name }}</h3>
            <p class="category-desc">{{ category.description }}</p>
            <span class="category-count">{{ category.count }} 个角色</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const searchKeyword = ref('')
const loading = ref(false)
const popularRoles = ref([])

const categories = ref([
  { id: 1, name: '虚拟女友', icon: '💕', description: '温柔体贴的AI女友', count: 12 },
  { id: 2, name: '学习助手', icon: '📚', description: '专业的教学伙伴', count: 8 },
  { id: 3, name: '心理咨询师', icon: '🧠', description: '倾听你的心声', count: 6 },
  { id: 4, name: '游戏伙伴', icon: '🎮', description: '一起玩游戏', count: 15 },
  { id: 5, name: '职场导师', icon: '💼', description: '职业发展指导', count: 9 },
  { id: 6, name: '创意伙伴', icon: '🎨', description: '激发创作灵感', count: 7 }
])

const loadPopularRoles = async () => {
  loading.value = true
  try {
    const token = localStorage.getItem('auth_token')
    const headers = token ? { 'Authorization': `Bearer ${token}` } : {}
    
    const res = await fetch('/api/roles/search?pageNo=1&pageSize=6&sortBy=usageCount&asc=false', { headers })
    const data = await res.json()
    popularRoles.value = data.data?.records || []
  } catch (e) {
    console.error('加载热门角色失败', e)
  } finally {
    loading.value = false
  }
}

const searchRoles = () => {
  if (searchKeyword.value.trim()) {
    router.push({ path: '/roles', query: { keyword: searchKeyword.value } })
  }
}

const startChat = async (role) => {
  try {
    const token = localStorage.getItem('auth_token')
    if (!token) {
      router.push('/login')
      return
    }
    
    // 创建新会话
    const res = await fetch('/api/conversations', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        roleId: role.id,
        roleVersion: 'latest'
      })
    })
    
    if (res.ok) {
      const data = await res.json()
      if (data.code === 0) {
        const conversationId = data.data
        
        // 增加角色使用量
        try {
          await fetch(`/api/roles/${role.id}/use`, {
            method: 'POST',
            headers: {
              'Authorization': `Bearer ${token}`
            }
          })
        } catch (e) {
          console.warn('增加使用量失败', e)
        }
        
        // 跳转到聊天页面
        router.push({ path: `/chat/${role.id}`, query: { conversationId } })
      } else {
        alert('创建会话失败：' + data.message)
      }
    } else {
      alert('创建会话失败，请重试')
    }
  } catch (e) {
    console.error('创建会话失败', e)
    alert('创建会话失败，请重试')
  }
}

const filterByCategory = (category) => {
  router.push({ path: '/roles', query: { category: category.name } })
}

onMounted(() => {
  loadPopularRoles()
})
</script>

<style scoped>
.home-page {
  height: 100%;
  overflow-y: auto;
}

.hero-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 80px 0;
  text-align: center;
}

.hero-content {
  width: 100%;
  padding: 0 32px;
}

.hero-title {
  font-size: 3rem;
  font-weight: 700;
  margin-bottom: 16px;
  line-height: 1.2;
}

.hero-subtitle {
  font-size: 1.25rem;
  margin-bottom: 32px;
  opacity: 0.9;
  line-height: 1.6;
}

.hero-search {
  display: flex;
  width: 100%;
  gap: 12px;
}

.search-input {
  flex: 1;
  padding: 16px 20px;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  background: rgba(255,255,255,0.9);
  color: #1f2937;
}

.search-input::placeholder {
  color: #6b7280;
}

.search-btn {
  padding: 16px 24px;
  background: #f59e0b;
  color: white;
  border: none;
  border-radius: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.search-btn:hover {
  background: #d97706;
  transform: translateY(-1px);
}

.content-section {
  padding: 60px 0;
}

.container {
  width: 100%;
  padding: 0 32px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
}

.section-header h2 {
  font-size: 2rem;
  font-weight: 700;
  color: #1f2937;
}

.view-all {
  color: #667eea;
  text-decoration: none;
  font-weight: 500;
  padding: 8px 16px;
  border-radius: 6px;
  transition: all 0.2s;
}

.view-all:hover {
  background: #f3f4f6;
}

.roles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
  margin-bottom: 60px;
}

.role-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.05);
  border: 1px solid #e5e7eb;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
  overflow: hidden;
}

.role-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 24px rgba(0,0,0,0.1);
  border-color: #667eea;
}

.role-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-bottom: 16px;
  overflow: hidden;
  background: linear-gradient(135deg, #667eea, #764ba2);
  display: flex;
  align-items: center;
  justify-content: center;
}

.role-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  color: white;
  font-size: 24px;
  font-weight: 600;
}

.role-name {
  font-size: 1.25rem;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 8px;
}

.role-desc {
  color: #6b7280;
  line-height: 1.5;
  margin-bottom: 16px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.role-stats {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.stat {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #6b7280;
  font-size: 14px;
}

.stat-icon {
  font-size: 16px;
}

.chat-btn {
  width: 100%;
  padding: 12px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.chat-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.categories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 24px;
}

.category-card {
  background: white;
  border-radius: 16px;
  padding: 32px 24px;
  text-align: center;
  box-shadow: 0 4px 6px rgba(0,0,0,0.05);
  border: 1px solid #e5e7eb;
  cursor: pointer;
  transition: all 0.3s;
}

.category-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 24px rgba(0,0,0,0.1);
  border-color: #667eea;
}

.category-icon {
  font-size: 3rem;
  margin-bottom: 16px;
}

.category-name {
  font-size: 1.25rem;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 8px;
}

.category-desc {
  color: #6b7280;
  margin-bottom: 12px;
}

.category-count {
  color: #667eea;
  font-weight: 500;
  font-size: 14px;
}

.loading-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 24px;
  margin-bottom: 60px;
}

.skeleton {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.05);
  border: 1px solid #e5e7eb;
}

.skeleton-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: #e5e7eb;
  margin-bottom: 16px;
  animation: pulse 2s infinite;
}

.skeleton-content {
  flex: 1;
}

.skeleton-title {
  height: 20px;
  background: #e5e7eb;
  border-radius: 4px;
  margin-bottom: 8px;
  animation: pulse 2s infinite;
}

.skeleton-desc {
  height: 16px;
  background: #e5e7eb;
  border-radius: 4px;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

@media (max-width: 768px) {
  .hero-title {
    font-size: 2rem;
  }
  
  .hero-subtitle {
    font-size: 1rem;
  }
  
  .hero-search {
    flex-direction: column;
  }
  
  .roles-grid {
    grid-template-columns: 1fr;
  }
  
  .categories-grid {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  }
}
</style>
